package person.zjh.kaoyansharehub.interceptor;


import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import person.zjh.kaoyansharehub.result.Result;
import person.zjh.kaoyansharehub.utils.JwtUtil;


/**
 * @description: 登入校验拦截器
 * @author 郑佳豪
 * @date 2025/1/17 3:31
 * @version 1.0
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("------进来拦截器---------");
        String token = request.getHeader("kaoyansharehub_front");
        Result result;
        if (token == null || token.isEmpty()) {
            result = Result.error("请携带token");
            response.setContentType("text/html;charset=utf8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }

        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            result = Result.error("请携带token");
            response.setContentType("text/html;charset=utf8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }

        return true;


    }
}
